HTTP routing
#
1. OverviewCellularJS is a protocol-agnostic framework, it can work well with HTTP. This article will show you how to use @cellularjs/express-proxy
with Express for routing HTTP request.
#
2. Express proxy@cellularjs/express-proxy
is a middleware. It will help you transform external message into internal message and vice versa. You can see the whole message flow here.
npm i @cellularjs/express-proxy express
#
3. Examples- Create a proxy for JSON API.
// $share/express-proxy/index.tsimport { send } from '@cellularjs/net';import { expressProxy, InputTransform, OutputTransform } from '@cellularjs/express-proxy';
const inputTransform: InputTransform = (req, proxyTo) => { return new IRQ( { to: proxyTo }, { ...req.query, ...req.params, ...req.body }, );}
const outputTransform: OutputTransform = (expressCtx, cellularCtx) => { const { res } = expressCtx; const { irs } = cellularCtx;
res .status(irs.header.status) .json(irs.body);}
export const proxyTo = expressProxy( { inputTransform, outputTransform }, { send: (irq) => send(irq) },);
// some-where.tsimport * as express from 'express';import { Router } from 'express';import { proxyTo } from '$share/express-proxy';
const userRouter = Router();userRouter.get('/my-info', proxyTo('User:MyInfo'));
const app = express();app.use('/api/user', userRouter);
// ...
- Override base proxy config for specific endpoint.
// iam/$gateway/http/index.tsimport { Router } from 'express';import { proxyTo } from '$share/express-proxy';
export const userRouter = Router();
userRouter.get('/list-users', proxyTo('User:ListUsers', { outputTransform: (expressCtx, cellularCtx) => { const { res } = expressCtx; const { irs } = cellularCtx;
res.send(`<pre>${JSON.stringify(irs.body)}</pre>`); },}));